package com.ruoyi.auth.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.auth.constant.WxContants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.RemoteLogService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.LoginUserWXVO;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.SysUserAccount;
import com.ruoyi.system.api.model.LoginUser;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(SysLoginService.class);
    @Autowired
    private RemoteLogService remoteLogService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new BaseException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new BaseException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username);

        if (R.FAIL == userResult.getCode())
        {
            throw new BaseException(userResult.getMsg());
        }

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new BaseException("登录用户：" + username + " 不存在");
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");

            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        if (!SecurityUtils.matchesPassword(password, user.getPassword()))
        {
            remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码错误");
            throw new BaseException("用户不存在/密码错误");
        }
        remoteLogService.saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public LoginUserWXVO loginApplet(String code, String rawData, String signature , String encrypteData, String iv){
        LoginUserWXVO result = new LoginUserWXVO();
        //log.info("loginApplet: " + "code: " + code + " rowData:" + rawData + "encrypteData: " + encrypteData + " iv: " +iv);
        // openId and sessionKey
        JSONObject resultJson = getSessionKeyOrOpenId(code);
        String sessionKey = resultJson.getStr("session_key");
        String openId = resultJson.getStr("openid");
        log.info("session_key: " + sessionKey + " ,openid: " + openId);
        //获取加密信息
        JSONObject userInfo = getUserInfo( encrypteData, sessionKey, iv );
        //log.info("根据解密算法获取的userInfo="+userInfo);

        if (StringUtils.isEmpty(openId)){
            throw new BaseException("授权失败"+ resultJson.get("errmsg"));
        }
        // openId 获取后的业务逻辑实现,如获取用户信息或者未注册用户创建新账号等。
        //openId 查询sys_user_account,不存在插入；绑定已有账号
        //
        // 查询用户信息
        SysUserAccount search = new SysUserAccount();
        search.setWxId(openId);
        R<SysUserAccount> userResult = remoteUserService.getUserAccountInfo(search);
        if (R.FAIL == userResult.getCode())
        {
            throw new BaseException(userResult.getMsg());
        }

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            // 插入userAccount
            SysUserAccount userAccount = new SysUserAccount();
            userAccount.setWxId(openId);
            if(StringUtils.isNotEmpty(rawData)){
                JSONObject rawDataJson = JSONUtil.parseObj(rawData);
                String nickName = rawDataJson.getStr( "nickName" );
                String avatarUrl = rawDataJson.getStr( "avatarUrl" );
                String gender  = rawDataJson.getStr( "gender" );
                String city = rawDataJson.getStr( "city" );
                String country = rawDataJson.getStr( "country" );
                String province = rawDataJson.getStr( "province" );
                userAccount.setWxName(nickName);
            }
            userAccount.setPhone(userInfo.getStr("phoneNumber"));
            remoteUserService.addUserAccountInfo(userAccount);
        }else {
            log.info("用户openid已存在,不需要插入");
            if(StringUtils.isEmpty(userResult.getData().getName())){
                result.setBind(false);
            }else {
                R<LoginUser> loginUserR = remoteUserService.getUserInfo(userResult.getData().getName());
                if (R.FAIL == loginUserR.getCode())
                {
                    throw new BaseException(userResult.getMsg());
                }
                result.setBind(true);
                result.setLoginUser(loginUserR.getData());
            }
        }
//        LoginUser userInfo = userResult.getData();
//        SysUser user = userResult.getData().getSysUser();
        //userInfo.put( "balance",user.getUbalance() );
        result.getResultMap().put("userInfo",userInfo);

        return result;

        //return new LoginUser(new WxUser(openId, sessionKey));
    }

    private JSONObject getSessionKeyOrOpenId(String code){
        //微信端登录code
        Map<String,Object> params = new HashMap<>();
        params.put("appid", WxContants.WX_LOGIN_APPID);
        params.put("secret",WxContants.WX_LOGIN_SECRET);
        params.put("grant_type",WxContants.WX_LOGIN_GRANT_TYPE);
        params.put("js_code",code);

        //        像微信服务器发送请求
        String wxRequestResult = HttpUtil.get(WxContants.WX_LOGIN_URL, params);
        log.info("wxRequest: " + wxRequestResult);
        JSONObject resultJson = JSONUtil.parseObj(wxRequestResult);
        return resultJson;
    }

    private JSONObject getUserInfo(String encryptedData,String sessionKey,String iv){
        if(StringUtils.isEmpty(sessionKey)){
            return null;
        }
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init( Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONUtil.parseObj(result);
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidParameterSpecException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public void logout(String loginName)
    {
        remoteLogService.saveLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    public LoginUserWXVO bindApplet(String username, String password,String phoneNumber) {
        LoginUserWXVO result = new LoginUserWXVO();
        // 账号密码验证，
        LoginUser userInfo = this.login(username, password);
        userInfo.setUserid(userInfo.getSysUser().getUserId());
        userInfo.setUsername(userInfo.getSysUser().getUserName());
        result.setLoginUser(userInfo);
        // 通过更新sys-user_account表
        // 查询用户信息
        SysUserAccount search = new SysUserAccount();
        search.setPhone(phoneNumber);
        R<SysUserAccount> userResult = remoteUserService.getUserAccountInfo(search);

        if (StringUtils.isNotNull(userResult) && StringUtils.isNotNull(userResult.getData()))
        {
            // 更新 userAccount
            SysUserAccount userAccount = userResult.getData();
            userAccount.setUserId(userInfo.getUserid().toString());
            userAccount.setName(userInfo.getUsername());
            remoteUserService.updateUserAccountInfo(userAccount);
        }else {
            log.info("绑定微信账号，用户未授权");
        }
        result.setBind(true);
        //生成token
        result.getResultMap().put("token", tokenService.createWxToken(userInfo));
        result.getResultMap().put("userInfo",userInfo.getSysUser());
        return result;
    }

    //public String loginApplet(String openId, String sessionKey) {
       // LoginUser loginUser = new LoginUser(new WxUser(openId, sessionKey));
//        tokenService.createWxToken(loginUser);
//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(openId, sessionKey);
//        authenticationToken.setDetails(loginUser);
//        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        // 生成token
//        return tokenService.createToken(loginUser);
       // return null;
    //}
}
